<template>
  <view class="user-edit-page">
    <!-- 头像修改区域 -->
    <view class="avatar-section">
      <text class="section-title">头像</text>
      <button class="avatar-btn" open-type="chooseAvatar" @click="handleChooseAvatar">
        <image class="avatar-img" :src="getFullPath(avatarUrl)" mode="aspectFill" />
      </button>
      <text class="tip-text">点击头像修改（支持JPG/PNG）</text>
    </view>

    <!-- 昵称修改区域 -->
    <view class="nickname-section">
      <text class="section-title">昵称</text>
      <nut-input v-model="nickname" type="nickname" placeholder="请输入昵称" border
        :max-length="20" class="nickname-input" />
      <text class="tip-text">支持特殊符号和emoji表情</text>
    </view>

    <!-- 注册时间显示区域 -->
    <!-- <view class="register-time-section" @tap="navigateToStoreMap">
      <text class="section-title">注册时间</text>
      <view class="time-info">
        <view class="time-display">
          <text class="time-text">{{ formattedCreateTime }}</text>
        </view>
        <view class="time-detail">
          <text class="detail-text">已加入 {{ daysSinceRegister }} 天</text>
        </view>
        <view class="store-access">
          <text class="store-text">查看附近店铺</text>
          <view class="arrow-icon">→</view>
        </view>
      </view>
    </view> -->

    <!-- 提交按钮 -->
    <nut-button type="primary" block class="submit-btn" @click="handleSubmit" :disabled="!isFormChanged">
      保存修改
    </nut-button>

    <!-- 头像预览弹窗 -->
    <nut-popup position="center" v-model:visible="showAvatarPreview" round>
      <image :src="tempAvatar" mode="aspectFit" class="avatar-preview" />
      <nut-button type="primary" @click="uploadAvatar" class="confirm-btn">
        确认使用
      </nut-button>
    </nut-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import Taro from '@tarojs/taro'
import { showToast, showLoading, hideLoading } from '@tarojs/taro'
import { useUserStore } from '@/store/user'
import pic from "@/assets/pic/tx.jpeg";
import { post,BASE_URL,getFullPath } from "@/utils/request";
import { storeToRefs } from "pinia"

// 用户状态管理
const userStore = useUserStore();
const {userInfo} = storeToRefs(userStore)
const defaultAvatar = pic // 默认头像


// 响应式数据
const avatarUrl = ref(userStore.userInfo.avatar_url || defaultAvatar)
const nickname = ref(userStore.userInfo.name || '')
const createTime = ref((userStore.userInfo as any).create_time || '') // 注册时间
const tempAvatar = ref('') // 临时头像路径
const showAvatarPreview = ref(false)
const originalAvatar = ref(avatarUrl.value)
const originalNickname = ref(nickname.value)

Taro.setNavigationBarTitle({
  title: "用户信息",
});

// 格式化注册时间
const formattedCreateTime = computed(() => {
  if (!createTime.value) return '暂无记录'

  try {
    const date = new Date(createTime.value)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')

    return `${year}-${month}-${day} ${hours}:${minutes}`
  } catch (error) {
    console.error('日期格式化错误:', error)
    return '时间格式错误'
  }
})

// 计算注册天数
const daysSinceRegister = computed(() => {
  if (!createTime.value) return 0

  try {
    const registerDate = new Date(createTime.value)
    const currentDate = new Date()
    const timeDifference = currentDate.getTime() - registerDate.getTime()
    const daysDifference = Math.floor(timeDifference / (1000 * 3600 * 24))

    return daysDifference > 0 ? daysDifference : 0
  } catch (error) {
    console.error('计算注册天数错误:', error)
    return 0
  }
})

// 计算表单是否修改
const isFormChanged = computed(() => {
  return avatarUrl.value !== originalAvatar.value || nickname.value !== originalNickname.value
})

// 上传后图片地址
const imageUrl = ref<string>('')
// 选择头像
const handleChooseAvatar = async () => {
  try {
    const res = await Taro.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera']
    })
    if (res.tempFilePaths && res.tempFilePaths.length > 0) {
      // avatarUrl.value = res.tempFilePaths[0]
      uploadAvatar(res.tempFilePaths[0])
    }
  } catch (err) {
    showToast({ title: '选择图片失败', icon: 'none' })
  }
}

// 上传到服务器
const uploadAvatar = async (filePath: string) => {
  // showAvatarPreview.value = true
  try {
    Taro.showLoading({ title: '上传中...' })
    const uploadRes = await Taro.uploadFile({
      url:getFullPath('/file/upload'),
      filePath,
      name: 'file',
      header: {
        'token': Taro.getStorageSync('token') ? Taro.getStorageSync('token') : ''
      }
    })
    console.log(uploadRes)
    Taro.hideLoading()
    //TODO：后续这里增加请求到后端接口，切换用户头像
    const data = JSON.parse(uploadRes.data)
    if (data.code === 0) {
      imageUrl.value = data.data
      avatarUrl.value = data.data
      showToast({ title: '上传成功', icon: 'success' })
    } else {
      showToast({ title: data.message || '上传失败', icon: 'none' })
    }
  } catch (err) {
    Taro.hideLoading()
    showToast({ title: '上传失败', icon: 'none' })
  }
}

// 昵称变更处理（兼容真机BUG）
const handleNicknameChange = (e) => {
  nickname.value = e.detail.value.trim().slice(0, 20)
}

// 提交修改
const handleSubmit = async () => {
  if (!validateForm()) return

  showLoading({ title: '保存中...' })
  const res = await post("/user/update", {
    name: nickname.value,
    avatarUrl: avatarUrl.value
  })
  console.log("res", res);
  if (res.code == 0) {
    showToast({ title: "保存成功", icon: "success" });
    userStore.fetchUserInfo()
  }
}

// 表单验证
const validateForm = (): boolean => {
  if (!nickname.value) {
    showToast({ title: '昵称不能为空', icon: 'none' })
    return false
  }

  if (nickname.value.length < 2) {
    showToast({ title: '昵称至少2个字符', icon: 'none' })
    return false
  }

  return true
}

// 导航到店铺地图页面
const navigateToStoreMap = () => {
  Taro.navigateTo({
    url: "/pages-detail/my/store-map",
  });
}
</script>

<style lang="scss">
/* 750rpx设计稿基准 */
$design-width: 750rpx;

.user-edit-page {
  padding: 40rpx;
  background-color: #f8f9fb;
  min-height: 100vh;
  box-sizing: border-box;
}

.section-title {
  display: block;
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 30rpx;
}

.avatar-section {
  background: #fff;
  border-radius: 24rpx;
  padding: 40rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.03);

  .avatar-btn {
    padding: 0;
    background: transparent;
    border: none;
    line-height: 1;

    &::after {
      border: none;
    }
  }
}

.nickname-section {
  background: #fff;
  border-radius: 24rpx;
  padding: 40rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.03);

  .nut-input {
    margin: 20rpx 0 !important;
    padding: 0 !important;
  }

  .nickname-input {
    border-radius: 16rpx;
    overflow: hidden;
    width: 100%;
    display: flex;
    border: 2rpx solid #eee;
    padding: 0 20rpx;
    height: 100rpx;
    font-size: 32rpx;
  }
}

.register-time-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 24rpx;
  padding: 40rpx;
  box-shadow: 0 15rpx 35rpx rgba(102, 126, 234, 0.2);
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;

  &::before {
    content: '';
    position: absolute;
    top: -50%;
    right: -50%;
    width: 200%;
    height: 200%;
    background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
    opacity: 0;
    transition: opacity 0.3s ease;
  }

  &:active {
    transform: translateY(4rpx);
    box-shadow: 0 8rpx 20rpx rgba(102, 126, 234, 0.3);

    &::before {
      opacity: 1;
    }
  }

  .section-title {
    color: #fff !important;
    font-weight: 600;
    text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
  }

  .time-info {
    .time-display {
      padding: 24rpx 0;
      border-bottom: 1rpx solid rgba(255, 255, 255, 0.2);

      .time-text {
        font-size: 34rpx;
        color: #fff;
        font-weight: 600;
        text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
      }
    }

    .time-detail {
      padding: 20rpx 0;
      border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);

      .detail-text {
        font-size: 28rpx;
        color: rgba(255, 255, 255, 0.9);
        display: flex;
        align-items: center;

        &::before {
          content: '🎉';
          margin-right: 8rpx;
          font-size: 24rpx;
        }
      }
    }

    .store-access {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 20rpx 0 0;

      .store-text {
        font-size: 26rpx;
        color: rgba(255, 255, 255, 0.9);
        font-weight: 500;
      }

      .arrow-icon {
        font-size: 32rpx;
        color: #fff;
        font-weight: bold;
        transform: translateX(0);
        transition: transform 0.3s ease;
      }
    }

    &:active .arrow-icon {
      transform: translateX(8rpx);
    }
  }
}

.tip-text {
  display: block;
  font-size: 26rpx;
  color: #999;
  margin-top: 20rpx;
}

.submit-btn {
  margin-top: 80rpx;
  height: 96rpx;
  border-radius: 48rpx;
  font-size: 34rpx;
  // background: linear-gradient(90deg, #ff5e3a, #ff2a6a);
  border: none;

  &:disabled {
    opacity: 0.6;
  }
}

.avatar-preview {
  width: 80vw;
  height: 80vw;
  max-width: 600rpx;
  max-height: 600rpx;
}

.confirm-btn {
  margin-top: 40rpx;
  width: 100%;
  border-radius: 48rpx;
  height: 88rpx;
}

.avatar-img {
  width: 160rpx;
  height: 160rpx;
  border-radius: 50%;
  background: #999;
}

/* 响应式适配 */
@media (min-width: 600rpx) {
  .user-edit-page {
    padding: 60rpx;
  }
}
</style>
